<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/config.php');

class JVMySQL
{
	protected $connection;
	protected $dbname;
	
	public function __construct($type, $host, $user, $password, $dbname)
	{
		$this->connection = mysql_pconnect($host, $user, $password);
		if (!$this->connection)
		{
			throw new PsException('Unable to connect to database {'.mysql_error().'}');
		}
		
		$this->dbname = $dbname;
		$isDBSelected = mysql_select_db($dbname, $this->connection);
		if (!$isDBSelected)
		{
			throw new PsException('Unable to connect to database {'.mysql_error().'}');
		}
		
		$this->exec("SET NAMES utf8");
	}
	
	public function quote($value)
	{
		return "'" . mysql_escape_string($value) . "'";
	}
	
	public function exec($sql)
	{
		return $this->query($sql);
	}
	
	public function query($sql)
	{
		$isDBSelected = mysql_select_db($this->dbname, $this->connection);
		if (!$isDBSelected)
		{
			throw new Exception('Unable to connect to database {'.mysql_error().'}');
		}
		
		$result = mysql_query($sql, $this->connection);
			
		if (!$result)
		{
			trigger_error('SQL error ' . mysql_error() . ' on query :<hr />' . $sql);
		}
		return $result;
	}
	
	public function row($result)
	{
		return mysql_fetch_array($result);
	}
	
	public function getRow($sql)
	{
		$result = $this->query($sql);
		return ($this->row($result));
	}
	
	public function insert($table, $data)
	{
		$fields = array_keys($data);
		$values = array_values($data);
		$values = array_map(array($this, 'quote'), $values);
		
		$sql = 'INSERT INTO ' . $table . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';
		return $this->exec($sql);
	}
	
	public function update($table, $data, $where = '')
	{
		$update = array();
		foreach ($data AS $key => $value)
		{
			if(is_bool($value))
			{
				$value = $value ? 1 : 0;
			}
			$update[] = $key . ' = ' . (is_null($value) ? 'NULL' : $this->quote($value));
		}
		
		$sql = 'UPDATE ' . $table . ' SET ' . implode(', ', $update) . (($where) ? " WHERE $where" : '');
		return $this->exec($sql);
	}
	
	public function delete($table, $where = '')
	{
		if (!$where)
		{
			$sql = "TRUNCATE $table";
		}
		else
		{
			$sql = "DELETE FROM $table WHERE $where";
		}
		return $this->exec($sql);
	}
	
	public function getLastId()
	{
		return mysql_insert_id($this->connection);
	}
	
	protected static $data = null;
	
	/**
	 * get connection
	 *
	 * @return JVMySQL
	 */
	public static function get()
	{
		if(self::$data)
		{
			return self::$data;
		}
		else 
		{
			$bdData = getBd();
			
			return new JVMySQL(
				$bdData['type'],
				$bdData['host'],
				$bdData['login'],
				$bdData['mdp'],
				$bdData['dbname']
			);
		}
	}
}